package com.example.androidmqtt.Controller;

import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.example.androidmqtt.Vo.ResultData;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;

@CrossOrigin
@EnableAsync
@RestController
public class FileController {

    private static String storePath =System.getProperty("user.dir")+"/static/";
    private static final String serverUrl = "https://android.nightowl.top/static/";
//
    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
    public ResultData fileUpload(@RequestParam(value = "file", required = true) MultipartFile file) {
        if (file.isEmpty()) {
            return ResultData.error("上传图片不存在~");
        } else {
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));//只支持JPG、JPEG、PNG
            // 验证上传的文件是否图片
            if (!".jpg".equalsIgnoreCase(suffixName)
                    && !".jpeg".equalsIgnoreCase(suffixName)
                    && !".png".equalsIgnoreCase(suffixName)) {
                return ResultData.error("只支持JPG、JPEG、PNG三种类型~");
            }
            File dest = new File(storePath + fileName);
            if (fileName.startsWith("/") && !dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                System.out.println("输出文件路径：" + serverUrl + fileName);
                return ResultData.success("上传成功~", 0, serverUrl + fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultData.error("图片上传失败~");
            }
        }
    }
}
